<!--
 * @Descripttion: 系统计划任务配置
 * @version: 1.2
 * @Author: sakuya
 * @Date: 2021年7月7日09:28:32
 * @LastEditors: sakuya
 * @LastEditTime: 2021年7月10日20:56:47
-->

<template>
	<el-main>
		<el-row :gutter="15" v-loading="loading">
			<el-col :xl="6" :lg="6" :md="8" :sm="24" :xs="24" v-for="item in list" :key="item.id">
				<el-card class="task task-item" shadow="hover" style="position: relative;">
					<h2 class="beyond_handle">{{ item.jobDesc }}</h2>
					<el-button class="btn" text :icon="item.icon ? item.icon : 'el-icon-pie-chart'" style="position: absolute; top:0px; right:0px" @click="showChartsSwitch(item)"></el-button>
					<ul>
						<li>
							<h4>执行器</h4>
							<p class="width_size_left">{{ item.executorHandler }}</p>
						</li>
						<li>
							<h4>定时规则</h4>
							<p class="width_size_right">{{ item.scheduleConf }}</p>
						</li>
					</ul>
					<div style="width: 170px; position: absolute; top: 57px;right:8px;overflow: hidden">
						<scEcharts v-if="item.showCharts" height="126px" width="180px" :option="item.option ? item.option : setChartsInfo(item)" style="position: relative;top: -32px"></scEcharts>
						<ul v-else>
							<li>
								<h4>在线机器地址</h4>
								<el-scrollbar height="68px">
									<p v-for="tag in item.onlineAddress" :key="tag">{{tag}}</p>
								</el-scrollbar>
							</li>
						</ul>
					</div>

					<div class="bottom">
						<div class="state">
							<el-tag v-if="item.triggerStatus=='1'" size="small">{{ item.triggerStatusName }}</el-tag>
							<el-tag v-if="item.triggerStatus=='0'" size="small" type="info">
								{{ item.triggerStatusName }}
							</el-tag>
						</div>
						<div class="handler">
							<el-popconfirm :title="item.triggerStatus == '0' ? '确定立即启动吗？' : '确定立即停止吗？'"
										   @confirm="run(item)" v-if="this.$TOOL.auth.verification(['task:switch'])">
								<template #reference>
									<el-button v-if="item.triggerStatus=='0'" type="primary" icon="el-icon-caret-right" class="startIcon"
											   circle></el-button>
									<el-button v-if="item.triggerStatus=='1'" type="primary" class="stopIcon"
											   circle></el-button>
								</template>
							</el-popconfirm>
							<el-dropdown trigger="click" v-if="this.$TOOL.auth.verification(['task:trigger','task:log','task:edit','task:delete'])">
								<el-button type="primary" icon="el-icon-more" circle plain></el-button>
								<template #dropdown>
									<el-dropdown-menu>
										<el-dropdown-item @click="trigger(item)" v-if="this.$TOOL.auth.verification(['task:trigger'])">执行一次</el-dropdown-item>
										<el-dropdown-item @click="logs(item)" v-if="this.$TOOL.auth.verification(['task:log'])">查询日志</el-dropdown-item>
										<el-dropdown-item @click="edit(item)" divided  v-if="this.$TOOL.auth.verification(['task:edit'])">编辑</el-dropdown-item>
										<el-dropdown-item @click="del(item)"  v-if="this.$TOOL.auth.verification(['task:delete'])">删除</el-dropdown-item>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
						</div>
					</div>
				</el-card>
			</el-col>
			<el-col :xl="6" :lg="6" :md="8" :sm="12" :xs="24" v-if="this.$TOOL.auth.verification(['task:add'])">
				<el-card class="task task-add" shadow="never" @click="add">
					<el-icon>
						<el-icon-plus/>
					</el-icon>
					<p>添加计划任务</p>
				</el-card>
			</el-col>
		</el-row>
	</el-main>

	<save-dialog v-if="dialog.save" ref="saveDialog" @success="getInitData" @closed="dialog.save=false"></save-dialog>
	<trigger-dialog v-if="dialog.trigger" ref="triggerDialog" @success="getInitData" @closed="dialog.trigger=false"></trigger-dialog>

	<el-drawer title="计划任务日志" v-model="dialog.logsVisible" :size="1000" direction="rtl" destroy-on-close>
		<logs ref="logDialog"></logs>
	</el-drawer>


</template>

<script>
import saveDialog from './save'
import triggerDialog from './trigger'
import logs from './logs'
import scEcharts from '@/components/scEcharts';

export default {
	name: 'task',
	components: {
		saveDialog,
		triggerDialog,
		logs,
		scEcharts
	},
	data() {
		return {
			loading: false,
			dialog: {
				save: false,
				logsVisible: false,
				trigger: false
			},
			list: [],
			options:[]
		}
	},
	created() {
		window.onresize = () => {
			return (() => {
				// 监听浏览器宽高变化
				this.headerHeight = this.$TOOL.page.updateHeight();
			})()
		}
	},
	mounted() {
		this.getInitData()
	},
	methods: {

		async showChartsSwitch(task) {
			if (task.showCharts) {
				task.showCharts = false
				task.icon = "el-icon-pie-chart"
			} else {
				task.showCharts = true
				task.icon = "el-icon-view"
				// 获取job任务的 成功数和失败数量（当月起始时间至今）
				let first = this.getFirst();
				let now = this.getNow();

				let res = await this.$API.system.task.statistics.get({
					jobId: task.id,
					startTime: first,
					endTime: now
				});
				if(res.status == 200){
					this.setChartsInfo(task, res.data.successQuantity, res.data.errorQuantity)
				}
			}
		},

		setChartsInfo(item, successNum = 0, errorNum = 0){
			item.option={
				legend: {},
				tooltip: {},
				dataset: {
					source: [
						['', successNum, errorNum]
					]
				},
				xAxis: { type: 'category' },
				yAxis: {},
				// Declare several bar series, each will be mapped
				// to a column of dataset.source by default.

				series: [{ type: 'bar' ,color: 'rgb(114,224,136)'}, { type: 'bar', color: 'rgb(227,104,112)'}]
			}
		},

		/**
		 * 执行一次
		 * @returns {Promise<void>}
		 */
		async trigger(task){
			this.dialog.trigger = true
			this.$nextTick(() => {
				this.$refs.triggerDialog.open().setData(task)
			});
		},

		logs(data) {
			this.dialog.logsVisible = true
			this.$nextTick(()=>{
				this.$refs.logDialog.search = {jobId: data.id}
				this.$refs.logDialog.setData(data)
			} )
		},

		/**
		 * 加载初始化数据
		 * @returns {Promise<void>}
		 */
		async getInitData() {
			this.loading = true
			let res = await this.$API.system.task.list.get();
			this.list = res.data
			this.loading = false
		},

		add() {
			this.dialog.save = true
			this.$nextTick(() => {
				this.$refs.saveDialog.open()
			})
		},
		edit(task) {
			this.dialog.save = true
			this.$nextTick(() => {
				this.$refs.saveDialog.open('edit').setData(task)
			})
		},
		async del(task) {
			this.$confirm(`确认删除 ${task.jobDesc} 计划任务吗？`, '提示', {
				type: 'warning',
				confirmButtonText: '删除',
				confirmButtonClass: 'el-button--danger'
			}).then(async () => {
				let res = await this.$API.system.task.del.delete({"id":task.id});
				if (res.status != 200) {
					return;
				}
				this.$message.success(`计划任务删除成功：${task.jobDesc}`)
				this.list.splice(this.list.findIndex(item => item.id === task.id), 1)
				this.getInitData();
			}).catch(() => {
				//取消
			})
		},


		/**
		 * 启动｜停止定时任务
		 * @param task
		 */
		async run(task) {
			if (task.triggerStatus == 0) {
				let res = await this.$API.system.task.switch.get({"id": task.id, "switchType": 1});
				if (res.status != 200) {
					return;
				}
				this.$message.success(`计划任务启动成功：${task.jobDesc}`)
			}else {
				let res = await this.$API.system.task.switch.get({"id": task.id, "switchType": 0});
				if (res.status != 200) {
					return;
				}
				this.$message.success(`计划任务停止成功：${task.jobDesc}`)
			}
			this.getInitData();
		},

		/**
		 * 获取当月起始时间
		 * @returns {string}
		 */
		getFirst() {
			var date = new Date();
			date.setDate(1);
			var cTime = new Date(new Date(date).toLocaleDateString()).getTime();
			//将时间戳转换成时间格式
			var date1 = new Date(cTime);
			var year = date1.getFullYear();
			var month = date1.getMonth() + 1;
			var day = date1.getDate();
			month = month < 10 ? "0" + month : month;
			day = day < 10 ? "0" + day : day;
			var ddate = year + '-' + month + '-' + day + " 00:00:00";
			return ddate;
		},

		/**
		 * 获取当前时间
		 * @returns {string}
		 */
		getNow() {
			var date = new Date();
			var year = date.getFullYear();
			var month = date.getMonth() + 1;
			var day = date.getDate();

			let hours = String(date.getHours()).length < 2 ? "0"+date.getHours(): date.getHours();
			let minutes = String(date.getMinutes()).length < 2 ? "0"+date.getMinutes(): date.getMinutes();
			let seconds = String(date.getSeconds()).length < 2 ? "0"+date.getSeconds(): date.getSeconds();

			month = month < 10 ? "0" + month : month;
			day = day < 10 ? "0" + day : day;
			var ddate = year + '-' + month + '-' + day + " " + hours + ":" + minutes +":"+ seconds;
			return ddate;
		}
	}
}
</script>

<style scoped>
.task {
	height: 210px;
}

.task-item h2 {
	font-size: 15px;
	color: #3c4a54;
	padding-bottom: 15px;
}

.task-item li {
	list-style-type: none;
	margin-bottom: 10px;
}

.task-item li h4 {
	font-size: 12px;
	font-weight: normal;
	color: #999;
}

.task-item li p {
	margin-top: 5px;
}

.task-item .bottom {
	border-top: 1px solid #EBEEF5;
	text-align: right;
	padding-top: 10px;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.task-add {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	text-align: center;
	cursor: pointer;
	color: #999;
}

.task-add:hover {
	color: #409EFF;
}

.task-add i {
	font-size: 30px;
}

.task-add p {
	font-size: 12px;
	margin-top: 20px;
}

.dark .task-item .bottom {
	border-color: var(--el-border-color-light);
}

.stopIcon{
	width:32px;
	position: relative;
}

.stopIcon:after{
	content: "";
	display: block;
	width: 9px;
	height: 9px;
	background: #ffffff;
}
.startIcon{
	width:32px;
	font-size:18px;
}

.task-item .btn{
	display: none;
}

.task-item:hover .btn{
	display: block;
}
.beyond_handle{
	width: 100%;
	white-space:nowrap;
	overflow:hidden;
	text-overflow:ellipsis;
}
.width_size_left{
	width: 46%;
	white-space:nowrap;
	overflow:hidden;
	text-overflow:ellipsis;
}
.width_size_right{
	width: 54%;
	white-space:nowrap;
	overflow:hidden;
	text-overflow:ellipsis;
}

</style>
